#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2022-8-7 18:11
# @file     : analisis_branch
# @Software : PyCharm
# ======================================#
import argparse
import os
import sys

from git import Repo

git_repo_dir = "/opt/repository/project"
shell_bool = False if sys.platform.startswith("win") else True


def get_git_log_sha(git_log):
    git_log_sha = []
    for line in git_log.split('\n'):
        sha = line.strip()[0:7]
        git_log_sha.append(sha)
    return git_log_sha


def compare(release_shas, branch_shas):
    release_sha = None

    for branch_index, branch_sha in enumerate(branch_shas):
        try:
            release_index = release_shas.index(branch_sha)
            if release_shas[release_index + 1] == branch_shas[branch_index + 1]:
                release_sha = branch_sha
                break
        except:
            continue
    else:
        raise Exception("没有找到当前分支从release拉取的sha值，请确认当前对比分支是否是release拉取分支，或release分支拉取的分支！")

    print(f"compare sha: {release_sha}")
    return release_sha


def find_release_and_branch_sha(branch):
    """
    先看release sha
    然后看测试分支sha
    查找到重复的sha,然后查询测试分支重复的上一个的孩子sha是否和release一致，如果一直则说明这个分支是从这个release拉出来的
    """
    # 拉取代码
    os.chdir(git_repo_dir)
    print(f"current dir: {os.path.abspath(os.curdir)}")

    repo = Repo(".")
    git = repo.git
    git.checkout("release")

    # 清除gitlab已经清除的仓库
    prune_info = git.execute("git remote prune origin", shell=shell_bool)
    for prune in prune_info.split('\n'):
        if '[pruned]' in prune:
            prune_branch = prune.split('/')[-1]
            try:
                git.execute(f'git branch -D {prune_branch}')
                print(f"pruned branch: {prune_branch}")
            except Exception as e:
                pass
    git.execute("git pull", shell=shell_bool)
    # checkout branch
    git.checkout(branch)
    print(f"{git.execute('git branch', shell=shell_bool)}")
    git_release_log = git.execute("git log release --oneline --no-merges", shell=shell_bool)
    git_branch_log = git.execute(f"git log {branch} --oneline --no-merges", shell=shell_bool)
    release_sha = get_git_log_sha(git_release_log)
    branch_sha = get_git_log_sha(git_branch_log)

    pull_branch_sha = compare(release_sha, branch_sha)
    return pull_branch_sha


def arg_run():
    parse = argparse.ArgumentParser(description="compare sql and run!")
    # parse.add_argument("env", type=str, default="8080")
    parse.add_argument("branch", type=str, default="release")
    parse.add_argument("--sha", type=str, default="")
    # parse.add_argument("--exec_bool", type=str, default="是")
    args = parse.parse_args()
    # print("\n".join([f"{key}: {value}" for key, value in args.__dict__.items()]))
    # env = args.env.strip()
    branch = args.branch.strip()
    sha = args.sha.strip()
    # exec_bool = args.exec_bool.strip() == "是"
    # find_release_and_branch_sha(env, branch, sha=sha, exec_bool=exec_bool)
    branch = branch.split("/")[-1]
    if branch == "release" or branch == "master":
        if not sha:
            raise Exception("master 或 release需要手动指定sha,sha不能为空！！")
        else:
            pull_release_sha = sha
    else:
        pull_release_sha = find_release_and_branch_sha(branch)
    print(f"当前分支 {branch} 从 release sha: {pull_release_sha} 拉取的分支")


def run(branch="origin/release", sha=None):
    branch = branch.split("/")[-1]
    if branch == "release" or branch == "master":
        if not sha:
            raise Exception("master 或 release需要手动指定sha,sha不能为空！！")
        else:
            pull_release_sha = sha
    else:
        pull_release_sha = find_release_and_branch_sha(branch)
    print(f"当前分支 {branch} 从 release sha: {pull_release_sha} 拉取的分支")


if __name__ == '__main__':
    if sys.platform.startswith("win"):
        run()
    else:
        arg_run()
